package com.common.base.utils

import android.os.Parcelable
import com.tencent.mmkv.MMKV

/**
 * 缓存工具类，替换SharedPreferences
 */
object SpUtils {
    private val mmkv = MMKV.defaultMMKV()

    // =====================Boolean=====================
    fun putBoolean(key: String, value: Boolean) {
        mmkv?.encode(key, value)
    }

    @JvmOverloads
    fun getBoolean(key: String, defValue: Boolean = false): Boolean {
        return mmkv?.decodeBool(key, defValue) ?: defValue
    }

    // =====================String=====================
    fun putString(key: String, value: String) {
        mmkv?.encode(key, value)
    }

    fun getString(key: String, defValue: String = ""): String {
        return mmkv?.decodeString(key, defValue) ?: ""
    }

    // =====================Parcelable=====================
    fun putParcelable(key: String, value: Parcelable) {
        mmkv?.encode(key, value)
    }

    fun <T : Parcelable> getParcelable(key: String, defValue: Class<T>): T? {
        return mmkv?.decodeParcelable(key, defValue)
    }


    // =====================Int=====================
    fun putInt(key: String, value: Int) {
        mmkv?.encode(key, value)
    }

    fun getInt(key: String, defValue: Int = 0): Int {
        return mmkv?.decodeInt(key, defValue) ?: defValue
    }

    // =====================Long=====================
    fun putLong(key: String, value: Long) {
        mmkv?.encode(key, value)
    }

    fun getLong(key: String, defValue: Long = 0): Long {
        return mmkv?.decodeLong(key, defValue) ?: defValue
    }


    // =====================Float=====================
    fun putFloat(key: String, value: Float) {
        mmkv?.encode(key, value)
    }

    fun getFloat(key: String, defValue: Float = 0f): Float {
        return mmkv?.decodeFloat(key, defValue) ?: defValue
    }

    // =====================Double=====================
    fun putDouble(key: String, value: Double) {
        mmkv?.encode(key, value)
    }

    fun getDouble(key: String, defValue: Double = 0.0): Double {
        return mmkv?.decodeDouble(key, defValue) ?: defValue
    }

    fun removeFromKey(key: String) {
        mmkv?.removeValueForKey(key)
    }

    fun containKey(key: String): Boolean{
        return mmkv?.containsKey(key) ?: false
    }

    fun clearAll(){
        mmkv?.clearAll()
    }

}